package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BusinessException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.utils.BeanHelper;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishMapper dishMapper;

    @CacheEvict(cacheNames = "setmeal:cache" , key = "#a0.categoryId")
    @Override
    public void save(SetmealDTO setmealDTO) {
        //1. 保存套餐的基本信息
        Setmeal setmeal = BeanHelper.copyProperties(setmealDTO, Setmeal.class);
        setmeal.setStatus(StatusConstant.DISABLE);
        setmealMapper.insert(setmeal);

        //2. 获取套餐的主键ID
        Long setmealId = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(!CollectionUtils.isEmpty(setmealDishes)){
            setmealDishes.stream().forEach(setmealDish -> {
                setmealDish.setSetmealId(setmealId);
            });
        }

        //3. 保存套餐和菜品的关系
        setmealDishMapper.insertBatch(setmealDishes);
    }


    @Override
    public PageResult page(SetmealPageQueryDTO setmealPageQueryDTO) {
        //1. 设置分页参数
        PageHelper.startPage(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        //2. 执行查询
        List<SetmealVO> setmealVOList = setmealMapper.listVo(setmealPageQueryDTO);

        //3. 解析并封装结果
        Page page = (Page) setmealVOList;
        return new PageResult(page.getTotal(), page.getResult());
    }


    @CacheEvict(cacheNames = "setmeal:cache" , allEntries = true)
    @Transactional
    @Override
    public void delete(List<Long> ids) {
        //1. 起售状态的套餐不可删除
        ids.forEach(id -> {
            Setmeal setmeal = setmealMapper.getById(id);
            if(StatusConstant.ENABLE == setmeal.getStatus()){
                throw new BusinessException(MessageConstant.SETMEAL_ON_SALE);
            }
        });

        //2. 删除套餐数据, 以及套餐与菜品的关联信息
        setmealMapper.deleteBatchByIds(ids);
        setmealDishMapper.deleteBatchBySetmealIds(ids);
    }

    @Override
    public SetmealVO getById(Long id) {
        //1. 根据ID查询套餐的基本信息
        Setmeal setmeal = setmealMapper.getById(id);

        //2. 根据套餐ID查询套餐关联的菜品列表
        List<SetmealDish> setmealDishList = setmealDishMapper.getBySetmealId(id);

        //3. 封装结果
        SetmealVO setmealVO = BeanHelper.copyProperties(setmeal, SetmealVO.class);
        if (setmealVO != null) {
            setmealVO.setSetmealDishes(setmealDishList);
        }
        return setmealVO;
    }


    @CacheEvict(cacheNames = "setmeal:cache" , allEntries = true)
    @Transactional
    @Override
    public void update(SetmealDTO setmealDTO) {
        //1. 修改套餐的基本信息
        Setmeal setmeal = BeanHelper.copyProperties(setmealDTO, Setmeal.class);
        setmealMapper.update(setmeal);

        Long setmealId = setmealDTO.getId();

        //2. 先删除套餐与菜品之间的关联关系 , 删除 setmeal_dish 中的数据
        setmealDishMapper.deleteBatchBySetmealIds(Collections.singletonList(setmealId));

        //3. 再插入套餐与菜品之间的关联关系 , 操作 setmeal_dish 表中的数据
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        if(!CollectionUtils.isEmpty(setmealDishes)) {
            setmealDishes.stream().forEach(setmealDish -> {
                setmealDish.setSetmealId(setmealId);
            });
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }


    @CacheEvict(cacheNames = "setmeal:cache" , allEntries = true)
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        //1. 如果是 起售 操作 , 判断当前套餐关联的菜品是否有停售的, 如果有, 不允许起售
        if (status == StatusConstant.ENABLE){
            List<Dish> dishList = dishMapper.getBySetmealId(id);
            if(!CollectionUtils.isEmpty(dishList)){
                dishList.stream().forEach(dish -> {
                    if(StatusConstant.DISABLE == dish.getStatus()){
                        throw new BusinessException(MessageConstant.SETMEAL_ENABLE_FAILED);
                    }
                });
            }
        }

        //2. 更新套餐的状态
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();
        setmealMapper.update(setmeal);
    }


    /**
     * 条件查询
     * @param setmeal
     * @return
     */
    @Cacheable(cacheNames = "setmeal:cache" , key = "#a0.categoryId")
    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        List<Setmeal> list = setmealMapper.list(setmeal);
        return list;
    }


    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }
}
